package com.imay.photopicker;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.imay.capturefilter.R;
import com.imay.capturefilter.filter.base.gpuimage.GPUImage;
import com.imay.capturefilter.utils.ICCons;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.capturefilter.widget.ClipImageView;
import com.imay.photopicker.activity.BaseActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ClipActivity extends BaseActivity implements View.OnClickListener {

    private Context mContext = this;

    private ClipImageView mClipImageView;   //预览图
    private GPUImage mGPUImage;
    private String mFilePath = "";
    private Bitmap mBitmap; //这是原图
    private boolean mIsUri = false;

    private int mDegree;    // 图片被旋转的角度
    private int mSampleSize;
    private int requestCode;

    public final static int CLIP_REQUEST_CODE_1 = 1;
    public final static int CLIP_REQUEST_CODE_2 = 2;
    private Dialog dialog;

    public static void startActivity(Activity activity, int requestCode, String path, View transitionView) {
        Intent intent = new Intent(activity, ClipActivity.class);
        intent.putExtra(ICCons.KEY_FILE_PATH, path);
        intent.putExtra("requestCode",requestCode);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.picker_activity_clip_image;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        Window window=getWindow();
        window.addFlags(flag);

        mFilePath = getIntent().getStringExtra(ICCons.KEY_FILE_PATH);
        String uri = getIntent().getStringExtra(ICCons.KEY_FILE_URI);
        if (!TextUtils.isEmpty(uri)) {
            mFilePath = ICUtils.getPathByUri(this, Uri.parse(uri));
            mIsUri = true;
        }
        requestCode = getIntent().getIntExtra("requestCode",-1);
        if(requestCode == CLIP_REQUEST_CODE_1){
            mIsUri = true;
        }else if(requestCode == CLIP_REQUEST_CODE_2){
            mIsUri = false;
        }
        initView();
        initData();
    }

    private void initView() {
        mGPUImage = new GPUImage(this);

        mClipImageView = $(R.id.clip_image_view);    //预览图

        $(R.id.picker_iv_use).setOnClickListener(this);
        $(R.id.picker_iv_give_up).setOnClickListener(this);
    }

    private void initData() {
        mClipImageView.setmInput(mFilePath);
        setImageAndClipParams();
    }

    /**
     * 大图裁剪
     */
    private void setImageAndClipParams() {
        mClipImageView.post(new Runnable() {
            @Override
            public void run() {
                mDegree = ICUtils.readPictureDegree(mFilePath);
                final boolean isRotate = (mDegree == 90 || mDegree == 270);

                final BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(mFilePath, options);

                // 如果图片被旋转，则宽高度置换
                int w = isRotate ? options.outHeight : options.outWidth;

                // 裁剪是宽高比例3:2，只考虑宽度情况，这里按border宽度的两倍来计算缩放。
                mSampleSize = ICUtils.findBestSample(w, mClipImageView.getClipBorder().width());

                options.inJustDecodeBounds = false;
                options.inSampleSize = mSampleSize;
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                final Bitmap source = BitmapFactory.decodeFile(mFilePath, options);

                if (source == null) {
                    mHandler.sendEmptyMessage(5);
                    return;
                }

                // 解决图片被旋转的问题
                if (mDegree == 0) {
                    mBitmap = source;
                } else {
                    final Matrix matrix = new Matrix();
                    matrix.postRotate(mDegree);
                    mBitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
                    if (mBitmap != source && !source.isRecycled()) {
                        source.recycle();
                    }
                }
                mClipImageView.setImageBitmap(mBitmap);
                mHandler.sendEmptyMessage(4);
            }
        });
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.picker_iv_give_up) {
            onBackPressed();
        } else if (id == R.id.picker_iv_use) {
            dialog = ICUtils.createDialog(this, getString(R.string.IC_img_msg_create));
            dialog.show();
            clipImage();
        }
    }

    @Override
    protected boolean useDynamicTitleBar() {
        return false;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    dialog.dismiss();
                    if (!mIsUri) {    //相册选择，不删除原文件
                        ICUtils.deleteFile(getBaseContext(), mFilePath);//取消或者Back键盘，也删除原文件
                    }
                    //刷新文件夹
                    String resultFilePath = (String) msg.obj;
                    refreshPicture(resultFilePath);
                    Intent intent = getIntent();
                    intent.putExtra(ICCons.KEY_FILE_PATH, resultFilePath);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case 5: //原图资源文件失败，原始数据是空的
                    try{
                        ICUtils.showToast(mContext, getResources().getString(R.string.IC_img_msg_source_error));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    onBackPressed();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void refreshPicture(String filePath) {
        if (ICUtils.hasKitkat()) {
            ICUtils.scanPhotos(filePath, this);
        } else {
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }

    private void clipImage() {
        findViewById(R.id.picker_iv_use).setEnabled(false);//禁止重复点击
        findViewById(R.id.picker_iv_give_up).setEnabled(false);//禁止重复点击
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap tempBitmap = ((BitmapDrawable) mClipImageView.getDrawable()).getBitmap();
                if (tempBitmap == null) {
                    tempBitmap = mBitmap;
                }
                Bitmap b = mClipImageView.createClippedBitmap(ICUtils.bmpToByteArray(tempBitmap, false));
                String path = saveImage(b);

                if (!b.isRecycled()) {
                    b.recycle();
                }
                Message message = Message.obtain();
                message.obj = path;
                message.what = 2;
                mHandler.sendMessage(message);
            }
        }).start();
    }

    private String saveImage(final Bitmap image) {
        File file = ICUtils.getOutputMediaFile(mContext);
        try {
            image.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    @Override
    public void onBackPressed() {
        if (!mIsUri) {    //相册选择，不删除原文件
            ICUtils.deleteFile(this, mFilePath);//取消或者Back键盘，也删除原文件
        }
        setResult(RESULT_CANCELED, getIntent());
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        // 释放图片资源
        if (mBitmap != null) {
            ICUtils.recycledBitmap(mBitmap);
        }
        super.onDestroy();
    }
}